package com.practice.search;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import com.practice.util.FileHelper;

public class WordProduct {
	private final static String DIR = "src/test/resources/com/practice/search";
	
	public void search() {
		int N = 30;	
		String content = FileHelper.readFile(DIR + "/dictionary.txt");
		String[] words = content.split("\n");
		ArrayList<String>[] set = new ArrayList[N];
		HashMap<Integer, String>[] map = new HashMap[N];
		
		for (int i=0; i<N; i++) {
			set[i] = new ArrayList<String>();
			map[i] = new HashMap<Integer, String>();
		}
		
		for (String word : words) {
			word = word.trim();
			set[word.length()].add(word);
		}
		
		for (int i=0; i<N; i++) {
			for (String word : set[i]) {
				int score = score(word);
				if (!map[i].containsKey(score)) {
					map[i].put(score, word);
				}
			}
		}
		
		ArrayList<Pair> pairs = new ArrayList<Pair>();
		for (int i=1; i<30; i++) {
			for (int j=i; j<30; j++) {
				pairs.add(new Pair(j, i));
			}
		}
		Collections.sort(pairs, new Comparator<Pair>(){
			public int compare(Pair a, Pair b) {
				return b.x * b.y - a.x * a.y;
			}
		});
		
		for (Pair p : pairs) {
			for (int i : map[p.x].keySet()) {
				for (int j : map[p.y].keySet()) {
					if ((i & j) == 0) {
						System.out.println(map[p.x].get(i) + " * " 
								+ map[p.y].get(j) + " = " + p.x*p.y);
						return;
					}
				}
			}
		}
	}
	
	private int score(String word) {
		int score = 0;
		for (int i=0; i<word.length(); i++) {
			score |= 1 << word.charAt(i) - 'a';
		}
		return score;
	}
	
	private class Pair {
		int x, y;
		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
	
	public static void main(String[] args) {
		long t0 = System.currentTimeMillis();
		new WordProduct().search();
		long t1 = System.currentTimeMillis();
		System.out.println("Search takes " + (t1 - t0));
	}
}
